package org.jeecg.glr.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.SysConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.SysUtil;
import org.jeecg.glr.entity.GlrSensor;
import org.jeecg.glr.entity.GlrSensorData;
import org.jeecg.glr.entity.GlrSensorSet;
import org.jeecg.glr.service.IGlrSensorDataService;
import org.jeecg.glr.service.IGlrSensorService;
import org.jeecg.glr.service.IGlrSensorSetService;
import org.jeecg.glr.service.IGlrVideoYsService;
import org.jeecg.glr.util.GLRConstant;
import org.jeecg.glr.util.HttpRequestUtil;
import org.jeecg.glr.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.lang.Math.round;

/**
 * @Description: 传感器数据管理
 * @Author: jeecg-boot
 * @Date:   2020-02-11
 * @Version: V1.0
 */
@RestController
@RequestMapping("/glr/glrSensorData")
@Slf4j
public class GlrSensoDataController extends JeecgController<GlrSensorData, IGlrSensorDataService> {
	@Autowired
	private IGlrSensorDataService glrSensorDataService;
	@Autowired
	private IGlrVideoYsService glrVideoYsService;
	@Resource
	private IGlrSensorSetService glrSensorSetService;
	@Autowired
	private IGlrSensorService glrSensorService;

	/**
	 * 分页列表查询
	 *
	 * @param glrSensorData
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<?> queryPageList(GlrSensorData glrSensorData,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		GlrSensorSet sensorset=glrSensorSetService.getSenSorSetByStatus();
		QueryWrapper<GlrSensorData> queryWrapper = QueryGenerator.initQueryWrapperCode(glrSensorData, req.getParameterMap());
		Page<GlrSensorData> page = new Page<GlrSensorData>(pageNo, pageSize);

		IPage<GlrSensorData> pageList = glrSensorDataService.page(page, queryWrapper);
		List<GlrSensorData> list = pageList.getRecords();
			for (GlrSensorData sensorData : list){
				GlrSensor sensor=glrSensorService.getGlrSensorByCode(sensorData.getSensorCode());
				sensorData.setSensorName(sensor.getName());
				if(sensorset!=null) {
					if (sensorData.getTemperature() > sensorset.getAlarmTemperature()) {
						sensorData.setAlarmFlagWd(true);
					}
					if (sensorData.getHumidity() > sensorset.getAlarmHumidity() || sensorData.getHumidity() < sensorset.getAlarmMinHumidity()) {
						sensorData.setAlarmFlagSd(true);
					}
					if (sensorData.getPm25() > sensorset.getAlarmPm25()) {
						sensorData.setAlarmFlagPm25(true);
					}
					if (sensorData.getPm10() > sensorset.getAlarmCo2()) {
						sensorData.setAlarmFlagCo2(true);
					}
				}
			}
		return Result.ok(pageList);
	}

	@RequestMapping(value = "tBSensorChartData")
	@ResponseBody
	public Map<String, Object> tBSensorChartData(String yearMonth,String sensorCode,int type){
		if (type==10){
			Map<String, Object> map =getYearMonth(yearMonth,sensorCode);
			return map;
		}else{
			Map<String, Object> map = null;
			try {
				map = getYearMonth20(yearMonth,sensorCode,type);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return map;
        }
	}

	private Map<String, Object> getYearMonth20(String yearMonth, String sensorCode,int type) throws  Exception {
		String year="";
		String month="";

		String[] sts=yearMonth.split("-");
		if (sts.length==2){
			year=sts[0];
			month=sts[1];
		}

		List<String> list=null;
		SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd");
		try {
			list = DateUtils.getMonthFullDay(sft.parse(year+"-"+month+"-01"));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		Map<String, Object> map = new HashMap<String, Object>();
		List<Double> maxList= new ArrayList<Double>();
		List<Double> avgList= new ArrayList<Double>();
		List<Double> minList= new ArrayList<Double>();

		String stType="";
		if (type==20) stType="temperature";
		if (type==21) stType="rainfall";
		if (type==22) stType="humidity";
		if (type==23) stType="noise";
		if (type==24) stType="pm25";
		if (type==25) stType="pm10";

		if (type==26) stType="airpressure";
		if (type==27) stType="wind_speed";
		if (type==28) stType="optical_radiation";
		if (type==29) stType="ultraviolet_ray";


		String sql = "select glr_sensor_data.id,date_format(glr_sensor_data.create_time,'%Y-%m-%d') as createTime,";
		sql = sql+""+stType+"_max as "+stType+"_max,"+stType+"_min as "+stType+"_min,"+stType+"_avg as "+stType+"_avg,";
		sql = sql+"round(max("+stType+"),1) as "+stType+"_max_01,round(min("+stType+"),1) as "+stType+"_min_01,round(avg("+stType+"),1) as "+stType+"_avg_01,";
		sql = sql+"glr_sensor.type " +
				"from glr_sensor_data " +
				"left join glr_sensor on glr_sensor.code=glr_sensor_data.sensor_code "+
				"where date_format(glr_sensor_data.create_time,'%Y-%m') = '"+year+"-"+month+"'  ";

		if (StringUtil.isNotEmpty(sensorCode)){
			sql=sql+" and sensor_code in (select sensor_code from (select sensor_code from glr_sensor_data where sensor_code='"+sensorCode+"' order by create_time desc limit 1)tt)";
		}else{
			sql=sql+" and sensor_code in (select sensor_code from (select sensor_code from glr_sensor_data order by create_time desc limit 1)tt)";
		}
		String userType= SysUtil.getUserInfo().getUserType();
		if(!userType.equals(SysConstant.SYS_USER_TYPE_ADMIN)&&!userType.equals(SysConstant.SYS_USER_TYPE_0)){
			sql=sql+"  and glr_sensor_data.sys_company_code='" + SysUtil.getUserInfo().getSysCompanyCode() + "'";
		}
		sql=sql+" GROUP BY date_format(glr_sensor_data.create_time,'%Y-%m-%d') " +
				" ORDER BY glr_sensor_data.create_time asc ";

		List<Map<String, Object>>  dataList= glrVideoYsService.doGetListForJdbc(sql);


		String yesterday1 = new SimpleDateFormat("yyyy-MM-dd").format(DateUtils.getEndDayOfMonth());
		String yesterday2 = new SimpleDateFormat("yyyy-MM-dd").format(DateUtils.getBeginDayOfMonth());
		Date d2 = sft.parse(yesterday2);
		Date d1 = sft.parse(yesterday1);
		Calendar dd1 = Calendar.getInstance();//定义日期实例
		dd1.setTime(d1);//设置日期起始时间
		dd1.add(Calendar.HOUR, 1);
		Calendar dd2 = Calendar.getInstance();//定义日期实例
		dd2.setTime(d2);//设置日期起始时间
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String thisDay=simpleDateFormat.format(new Date());
		List<String> newList = new ArrayList<>();
		while(dd2.getTime().before(dd1.getTime())) {
			String dateStr=simpleDateFormat.format(dd2.getTime());
			boolean bfind = false;
			for (Map<String, Object> data : dataList) {
				if(data.get("createTime").toString().equals(dateStr)){
					bfind=true;
					newList.add(data.get("createTime").toString());
					if(thisDay.equals(data.get("createTime"))){
						if (StringUtil.isNotEmpty(data.get(""+stType+"_max_01"))){
							maxList.add(Double.parseDouble(data.get(""+stType+"_max_01").toString()));
						}else{
							maxList.add(0d);
						}
						if (StringUtil.isNotEmpty(data.get(""+stType+"_min_01"))){
							minList.add(Double.parseDouble(data.get(""+stType+"_min_01").toString()));
						}else{
							minList.add(0d);
						}
						if (StringUtil.isNotEmpty(data.get(""+stType+"_avg_01"))){
							avgList.add(Double.parseDouble(data.get(""+stType+"_avg_01").toString()));
						}else{
							avgList.add(0d);
						}
					}else{
						if (StringUtil.isNotEmpty(data.get(""+stType+"_max"))){
							maxList.add(Double.parseDouble(data.get(""+stType+"_max").toString()));
						}else{
							maxList.add(0d);
						}
						if (StringUtil.isNotEmpty(data.get(""+stType+"_min"))){
							minList.add(Double.parseDouble(data.get(""+stType+"_min").toString()));
						}else{
							minList.add(0d);
						}
						if (StringUtil.isNotEmpty(data.get(""+stType+"_avg"))){
							avgList.add(Double.parseDouble(data.get(""+stType+"_avg").toString()));
						}else{
							avgList.add(0d);
						}
					}

					break;
				}
			}
			if(!bfind){
				newList.add(dateStr);
				maxList.add(0d);
				minList.add(0d);
				avgList.add(0d);
			}
			dd2.add(Calendar.DATE, 1);//进行当前日期月份加1
		}
		map.put("newList",newList);
		map.put("maxList",maxList);
		map.put("avgList",avgList);
		map.put("minList",minList);
		return map;

	}

	private Map<String, Object> getYearMonth(String yearMonth, String sensorCode) {
		String year="";
		String month="";

			String[] sts=yearMonth.split("-");
			if (sts.length==2){
				year=sts[0];
				month=sts[1];
			}

			List<String> list=null;
			SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd");
			try {
				list = DateUtils.getMonthFullDay(sft.parse(year+"-"+month+"-01"));
			} catch (ParseException e) {
				e.printStackTrace();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		List<Double> yuliangList= new ArrayList<Double>();
		List<Double> shiduList= new ArrayList<Double>();
		List<Double> qiyaList= new ArrayList<Double>();
		List<Double> fensuList= new ArrayList<Double>();
		List<String> fenxiangList= new ArrayList<String>();
		List<Double> wenduList= new ArrayList<Double>();
		List<Double> guangpuList= new ArrayList<Double>();
		List<String> ziwaixianList= new ArrayList<String>();
		List<Double> zaoshengList= new ArrayList<Double>();
		List<Double> pm25List= new ArrayList<Double>();
		List<Double> pm10List= new ArrayList<Double>();


		String sql = "select glr_sensor_data.id,date_format(glr_sensor_data.create_time,'%Y-%m-%d') as createTime,round(max(rainfall),1) as rainfall,round(avg(humidity),1) as humidity,round(avg(airpressure),1) as airpressure,round(avg(wind_Speed),1) as windSpeed," +
				"round(avg(wind_Direction),1) as windDirection,round(avg(temperature),1) as temperature,round(avg(optical_Radiation),1) as optical_Radiation,round(avg(ultraviolet_Ray),1) as ultravioletRay,round(avg(noise),1) as noise," +
				"round(avg(pm25),1) as pm25,round(avg(pm10),1) as pm10,glr_sensor.type " +
				"from glr_sensor_data " +
				"left join glr_sensor on glr_sensor.code=glr_sensor_data.sensor_code "+
				"where date_format(glr_sensor_data.create_time,'%Y-%m') = '"+year+"-"+month+"'  ";

		if (StringUtil.isNotEmpty(sensorCode)){
			sql=sql+" and sensor_code='"+sensorCode+"'";
		}
		String userType= SysUtil.getUserInfo().getUserType();
		if(!userType.equals(SysConstant.SYS_USER_TYPE_ADMIN)&&!userType.equals(SysConstant.SYS_USER_TYPE_0)){
			sql=sql+"  and glr_sensor_data.sys_company_code='" + SysUtil.getUserInfo().getSysCompanyCode() + "'";
		}
		sql=sql+"GROUP BY date_format(glr_sensor_data.create_time,'%Y-%m-%d') " +
				"ORDER BY glr_sensor_data.create_time asc";

		List<Map<String, Object>>  dataList= glrVideoYsService.doGetListForJdbc(sql);
		List<String> newList = new ArrayList<String>();
		for (Map<String, Object> data : dataList) {

			newList.add(data.get("createTime").toString());
			if (StringUtil.isNotEmpty(data.get("rainfall"))){
				yuliangList.add(Double.parseDouble(data.get("rainfall").toString()));
			}else{
				yuliangList.add(0d);
			}

			if (StringUtil.isNotEmpty(data.get("humidity"))){
				shiduList.add(Double.parseDouble(data.get("humidity").toString()));
			}else{
				shiduList.add(0d);
			}

			if (StringUtil.isNotEmpty(data.get("airpressure"))){
				qiyaList.add(Double.parseDouble(data.get("airpressure").toString()));
			}else{
				qiyaList.add(0d);
			}

			if (StringUtil.isNotEmpty(data.get("windSpeed"))){
				fensuList.add(Double.parseDouble(data.get("windSpeed").toString()));
			}else{
				fensuList.add(0d);
			}

			if (StringUtil.isNotEmpty(data.get("windDirection"))){
				fenxiangList.add(data.get("windDirection").toString());
			}else{
				fenxiangList.add("- -");
			}

			if (StringUtil.isNotEmpty(data.get("temperature"))){
				wenduList.add(Double.parseDouble(data.get("temperature").toString()));
			}else{
				wenduList.add(0d);
			}

			if (StringUtil.isNotEmpty(data.get("opticalRadiation"))){
				guangpuList.add(Double.parseDouble(data.get("opticalRadiation").toString()));
			}else{
				guangpuList.add(0d);
			}

			if (StringUtil.isNotEmpty(data.get("ultravioletRay"))){
				ziwaixianList.add(data.get("ultravioletRay").toString());
			}else{
				ziwaixianList.add("- -");
			}

			if (StringUtil.isNotEmpty(data.get("noise"))){
				zaoshengList.add(Double.parseDouble(data.get("noise").toString()));
			}else{
				zaoshengList.add(0d);
			}

			if (StringUtil.isNotEmpty(data.get("pm25"))){
				pm25List.add(Double.parseDouble(data.get("pm25").toString()));
			}else{
				pm25List.add(0d);
			}

			if (StringUtil.isNotEmpty(data.get("pm10"))){
				pm10List.add(Double.parseDouble(data.get("pm10").toString()));
			}else{
				pm10List.add(0d);
			}

		}
		int index=0;
		for (String s : list) {
			if(!newList.contains(s)){
				Map<String, Object> data = new HashMap<>();
				data.put("setCreateTime",s);
				dataList.add(data);
				yuliangList.add(index,0d);
				shiduList.add(index,0d);
				qiyaList.add(index,0d);
				fensuList.add(index,0d);
				fenxiangList.add(index,"0");
				wenduList.add(index,0d);
				guangpuList.add(index,0d);
				ziwaixianList.add(index,"0");
				zaoshengList.add(index,0d);
				pm25List.add(index,0d);
				pm10List.add(index,0d);
			}
			index++;
		}
		map.put("dateList",list);
		map.put("dataList",dataList);


		map.put("yuliangList",yuliangList);
		map.put("shiduList",shiduList);
		map.put("qiyaList",qiyaList);
		map.put("fensuList",fensuList);
		map.put("fenxiangList",fenxiangList);
		map.put("wenduList",wenduList);
		map.put("guangpuList",guangpuList);
		map.put("ziwaixianList",ziwaixianList);
		map.put("zaoshengList",zaoshengList);
		map.put("pm25List",pm25List);
		map.put("pm10List",pm10List);

		return map;
	}


	/**
	 * <p>
	 * 跳转到列表页面
	 * </p>
	 *
	 * @return
	 * @author:xiebin 2019-03-15
	 * @update: [updatedate] [changer][change description]
	 */
	@RequestMapping(value =  "tBHkBoxTaskChartData")
	@ResponseBody
	public Map<String, Object> tBHkBoxTaskChartData(String yearMonth) {
		String stSql="select \n" +
				"s_nap_time,\n" +
				"right(s_nap_time,2) as s_nap_time1,\n"+
				"sum(human0)+sum(human1)+sum(human2) as human,\n" +
				"sum(nonmotor0)+sum(nonmotor1)+sum(nonmotor2) as nonmotor,\n" +
				"sum(motor) as motor\n" +
				"from glr_video_traffic_monitoring \n" +
				"where 1=1";

		String yesterday1 ="";


		yesterday1 = yearMonth;

		stSql=stSql+" and s_nap_time between '"+yesterday1+" 00' and '"+yesterday1+" 24'";

		stSql=stSql+" group by s_nap_time";

		List<Map<String, Object>> ss=glrVideoYsService.doGetListForJdbc(stSql);
		List<Map<String, Object>> ss1=new ArrayList<>();

		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH");
		Date d2= null;
		try {
			d2 = simpleDateFormat.parse(yesterday1+" 00");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Date d1= null;
		try {
			d1 = simpleDateFormat.parse(yesterday1+" 23");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar dd1 = Calendar.getInstance();//定义日期实例
		dd1.setTime(d1);//设置日期起始时间
		dd1.add(Calendar.MINUTE,1);

		Calendar dd2 = Calendar.getInstance();//定义日期实例
		dd2.setTime(d2);//设置日期起始时间


		while(dd2.getTime().before(dd1.getTime())){//判断是否到结束日期

			String str = new SimpleDateFormat( "HH").format(dd2.getTime());
			String str1 = simpleDateFormat.format(dd2.getTime());
			//System.out.println(str);//输出日期结果

			boolean bfind=false;
			for(Map<String, Object> ss_1:ss){
				String ss_1_1=ss_1.get("s_nap_time1").toString();
				if (ss_1_1.equals(str)){
					bfind=true;
					ss1.add(ss_1);
					break;
				}
			}
			if (!bfind){
				Map<String, Object> ss_1=new HashMap<>();
				ss_1.put("s_nap_time",str1);
				ss_1.put("s_nap_time1",str);
				ss_1.put("human",0.00);
				ss_1.put("nonmotor",0.00);
				ss_1.put("motor",0.00);

				ss1.add(ss_1);
			}

			dd2.add(Calendar.HOUR, 1);//进行当前日期月份加1
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list",ss1);

		return map;
	}

	/**
	 *   添加
	 *
	 * @param glrSensorData
	 * @return
	 */
	@AutoLog(value = "添加传感器数据",logType= CommonConstant.LOG_TYPE_2)
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody GlrSensorData glrSensorData) {
		glrSensorDataService.save(glrSensorData);
		return Result.ok("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param glrSensorData
	 * @return
	 */
	@AutoLog(value = "修改传感器数据",logType= CommonConstant.LOG_TYPE_2)
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody GlrSensorData glrSensorData) {
		glrSensorDataService.updateById(glrSensorData);
		return Result.ok("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "删除传感器数据",logType= CommonConstant.LOG_TYPE_2)
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		glrSensorDataService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "批量删除传感器数据",logType= CommonConstant.LOG_TYPE_2)
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.glrSensorDataService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		GlrSensorData glrSensorData = glrSensorDataService.getById(id);
		if(glrSensorData==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(glrSensorData);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param glrSensorData
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GlrSensorData glrSensorData) {
        return super.exportXls(request, glrSensorData, GlrSensorData.class, "音柱管理");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, GlrSensorData.class);
    }

}
